//
//  SourceViewController.m
//  iMiniTao
//
//  Created by liunian on 13-8-16.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "SourceViewController.h"
#import "SourceManager.h"
#import "SourceViewCell.h"
#import "Source.h"
#import "MeSource.h"
#import "CustomKeyCell.h"


//频道背景颜色
#define COLOR_RGBA_SOURCE_BG  COLOR_RGBA(0, 174.0f, 238.0f, 0.6f)
#define COLOR_RGB_SOURCE_BG   COLOR_RGB(0, 174.0f, 238.0f)

#define COLOR_TABLECELL_SELECT_DAY      COLOR_RGB(234, 234, 234)
#define COLOR_TABLECELL_SELECT_NIGHT    COLOR_RGB(55, 55, 55)

#define COLOR_IMAGE_DEFAULT_BG        COLOR_RGB(221, 221, 221)
#define COLOR_IMAGE_DEFAULT_BG_NIGHT  COLOR_RGB(61, 61, 61)

#define kDefaultBottomBarHeight           38

@interface SourceViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,SourceManagerDelegate,SourceViewCellDelegate,RMSwipeTableViewCellDelegate,CustomKeyCellDelegate>
@property (nonatomic, retain) UITableView*tableView;
@property (nonatomic, retain) UIImageView          *navImageView;
@property (nonatomic, retain) UILabel       *theTitle;
@property (nonatomic, retain) UIImageView          *bottomImageView;
@property (nonatomic, retain) NSMutableArray        *sources;
@property (nonatomic, retain) NSMutableArray        *customSources;

@property (nonatomic, strong) NSIndexPath *selectedIndexPath;
@property (nonatomic, retain) UIActivityIndicatorView *indicatorView;
@end

@implementation SourceViewController

- (void)dealloc{
    BMLog(@"dealloc");
    _delegate = nil;
    [[SourceManager sharedManager] removeObserver:self];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view addSubview:self.navImageView];
    [self tableView];
    [self.view addSubview:self.bottomImageView];
    [[SourceManager sharedManager] addObserver:self];
    [[SourceManager sharedManager] requestAllSources];
    [[SourceManager sharedManager] getCustomSource];
    [self.indicatorView startAnimating];
    self.theTitle.text = @"栏目订阅";
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    [MobClick beginLogPageView:@"订阅视图"];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"订阅视图"];
}

- (void)back{
    
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
    }];
}
- (void)tableViewDidScrollToTop{
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return [self.customSources count];
    }
    return [self.sources count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *CellIdentifier = @"custom";
        
        CustomKeyCell *cell = (CustomKeyCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[CustomKeyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        MeSource *source = [self.customSources objectAtIndex:indexPath.row];
    
        cell.delegate = self;
        cell.demoDelegate = self;
        
        cell.meSource = source;
        cell.contentView.backgroundColor = [UIColor whiteColor];
        cell.nameLabel.frame = CGRectMake(58, 19, 210, 20);
        cell.summaryLabel.frame = CGRectZero;
    
        UIImage  *sub = nil;
        UIImage  *unSub = nil;
        sub = IMGNAMED(@"bg_subscribe.png");
        unSub = IMGNAMED(@"bg_unsubscribe.png");
        [cell.srcImageView setImageWithURL:[NSURL URLWithString:source.icon] placeholderImage:IMGFROMBUNDLE(@"bg_source_default.png")];
    
        cell.nameLabel.text = source.name;
        cell.subscribeImageView.image = sub;
        for (MeSource *meSource in [[SourceManager sharedManager] meSources]) {
            if ([meSource.name isEqualToString:source.name] && meSource.custom) {
                cell.subscribeImageView.image = unSub;
                break;
            }
        }
        return cell;
    }


    static NSString *CellIdentifier = @"SourceCell";
    
    SourceViewCell *cell = (SourceViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[SourceViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.delegate = self;
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    Source  *source = nil;
    cell.contentView.backgroundColor = [UIColor whiteColor];
    source = [self.sources objectAtIndex:[indexPath row]];

    cell.source = source;
    cell.nameLabel.text = source.name;
    
    if (cell.source.description) {
        cell.nameLabel.frame = CGRectMake(58, 12, 210, 20);
        cell.summaryLabel.frame = CGRectMake(58, 32, 210, 20);
        cell.summaryLabel.text = source.description;
    }else{
        cell.nameLabel.frame = CGRectMake(58, 19, 210, 20);
        cell.summaryLabel.frame = CGRectZero;
    }
    UIImage  *sub = nil;
    UIImage  *unSub = nil;
    sub = IMGNAMED(@"bg_subscribe.png");
    unSub = IMGNAMED(@"bg_unsubscribe.png");
    [cell.srcImageView setImageWithURL:[NSURL URLWithString:source.icon] placeholderImage:nil];

    cell.subscribeImageView.image = sub;
    for (MeSource *meSource in [[SourceManager sharedManager] meSources]) {
        if (meSource.itemtype == ITEMTYPECUZYITEM) {
            if ([meSource.themeid isEqualToString:cell.source.themeid]) {
                cell.subscribeImageView.image = unSub;
                break;
            }
        }else{
            if ([meSource.name isEqualToString:cell.source.name]) {
                cell.subscribeImageView.image = unSub;
                break;
            }
        }

    }
    
    return cell;
}

#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 58.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        if (self.customSources.count == 0) {
            return 0;
        }
    }
    if (section == 1) {
        if (self.sources.count == 0) {
            return 0;
        }
    }
	return 40.0f;
}

-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section {

    UILabel   *headLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 40.0f)];
    headLabel.textAlignment = [Util getAlign:ALIGNTYPE_CENTER];
    headLabel.font = FONT_CONTENT(18.0f);
    headLabel.textColor = COLOR_RGB(211.0f, 211.0f, 211.0f);
    headLabel.backgroundColor = COLOR_RGB(248, 248, 248);
    
    UIImage  *imgLine = IMGNAMED(@"bg_cell_separator_line.png");
    UIImageView  *lineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, headLabel.bounds.size.height-imgLine.size.height, headLabel.bounds.size.width, imgLine.size.height)];
    lineView.backgroundColor = [UIColor clearColor];
    lineView.image = imgLine;
    [headLabel addSubview:lineView];
    
    if (section == 0) {
        headLabel.text = @"我的栏目";
    }else{
        headLabel.text = @"精选分类";
    }
    return headLabel;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.selectedIndexPath.row != indexPath.row) {
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        [self resetSelectedCell];
    }
    if (self.selectedIndexPath.row == indexPath.row) {
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        [self resetSelectedCell];
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (self.selectedIndexPath) {
        [self resetSelectedCell];
    }
}

#pragma mark - CustomKeyCellDelegate

-(void)swipeTableViewCellDidDelete:(CustomKeyCell *)swipeTableViewCell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:swipeTableViewCell];
    [self.customSources removeObjectAtIndex:indexPath.row];
    [swipeTableViewCell resetContentView];
    [self.tableView beginUpdates];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
    [[SourceManager sharedManager] removeTheMeSource:swipeTableViewCell.meSource];
    [[SourceManager sharedManager] removeCustomSourceKeyWord:swipeTableViewCell.meSource.name];
}

-(void)handleSubscribeForCustomKeyCell:(CustomKeyCell *)cell{
    
    if (!cell.meSource) {
        return;
    }
    @synchronized(self){
        BOOL  isAdd = YES;
        for (MeSource *meSource in [[SourceManager sharedManager] meSources]) {
            if ([meSource.name isEqualToString:cell.meSource.name]) {
                if (meSource.custom) {
                    isAdd = NO;
                }
                
                break;
            }
        }
        
        
        if ([self.delegate respondsToSelector:@selector(handleMeSource:isAdd:)]) {
            [self.delegate handleMeSource:cell.meSource isAdd:isAdd];
        }
        UIImage  *sub = nil;
        UIImage  *unSub = nil;
        
        sub = IMGNAMED(@"bg_subscribe.png");
        unSub = IMGNAMED(@"bg_unsubscribe.png");
        
        cell.subscribeImageView.image = sub;
        for (MeSource *meSource in [[SourceManager sharedManager] meSources]) {
            if ([meSource.name isEqualToString:cell.meSource.name] && meSource.custom) {
                cell.subscribeImageView.image = unSub;
                break;
            }
        }
        if (isAdd) {
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                  cell.meSource.themeid, @"themeid",cell.meSource.name, @"name", nil];
            [MobClick event:@"SubscribeList" attributes:dict];
        }
    }
    
}
-(void)enterChannelForCustomKeyCell:(CustomKeyCell *)cell{

}
#pragma mark - RMSwipeTableViewCell delegate methods

-(void)swipeTableViewCellDidStartSwiping:(RMSwipeTableViewCell *)swipeTableViewCell {
    NSIndexPath *indexPathForCell = [self.tableView indexPathForCell:swipeTableViewCell];
    if (self.selectedIndexPath.row != indexPathForCell.row) {
        [self resetSelectedCell];
    }
}

-(void)resetSelectedCell {
    CustomKeyCell *cell = (CustomKeyCell*)[self.tableView cellForRowAtIndexPath:self.selectedIndexPath];
    [cell resetContentView];
    self.selectedIndexPath = nil;
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
}

-(void)swipeTableViewCellWillResetState:(RMSwipeTableViewCell *)swipeTableViewCell fromPoint:(CGPoint)point animation:(RMSwipeTableViewCellAnimationType)animation velocity:(CGPoint)velocity {
    if (velocity.x <= -500) {
        self.selectedIndexPath = [self.tableView indexPathForCell:swipeTableViewCell];
        swipeTableViewCell.shouldAnimateCellReset = NO;
        swipeTableViewCell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSTimeInterval duration = MAX(-point.x / ABS(velocity.x), 0.10f);
        [UIView animateWithDuration:duration
                              delay:0
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             swipeTableViewCell.contentView.frame = CGRectOffset(swipeTableViewCell.contentView.bounds, point.x - (ABS(velocity.x) / 150), 0);
                         }
                         completion:^(BOOL finished) {
                             [UIView animateWithDuration:duration
                                                   delay:0
                                                 options:UIViewAnimationOptionCurveEaseOut
                                              animations:^{
                                                  swipeTableViewCell.contentView.frame = CGRectOffset(swipeTableViewCell.contentView.bounds, -80, 0);
                                              }
                                              completion:^(BOOL finished) {
                                              }];
                         }];
    }
    // The below behaviour is not normal as of iOS 7 beta seed 1
    // for Messages.app, but it is for Mail.app.
    // The user has to pan/swipe with a certain amount of velocity
    // before the cell goes to delete-state. If the user just pans
    // above the threshold for the button but without enough velocity,
    // the cell will reset.
    // Mail.app will, however allow for the cell to reveal the button
    // even if the velocity isn't high, but the pan translation is
    // above the threshold. I am assuming it'll get more consistent
    // in later seed of the iOS 7 beta
    /*
     else if (velocity.x > -500 && point.x < -80) {
     self.selectedIndexPath = [self.tableView indexPathForCell:swipeTableViewCell];
     swipeTableViewCell.shouldAnimateCellReset = NO;
     swipeTableViewCell.selectionStyle = UITableViewCellSelectionStyleNone;
     NSTimeInterval duration = MIN(-point.x / ABS(velocity.x), 0.15f);
     [UIView animateWithDuration:duration
     animations:^{
     swipeTableViewCell.contentView.frame = CGRectOffset(swipeTableViewCell.contentView.bounds, -80, 0);
     }];
     }
     */
}
#pragma mark - SourceViewCellDelegate
-(void)handleSubscribeForSourceViewCell:(SourceViewCell *)cell{
    if (!cell.source) {
        return;
    }
     BMLog(@"3---:%@",cell.source.name);
    @synchronized(self){
        BOOL  isAdd = YES;
        for (MeSource *meSource in [[SourceManager sharedManager] meSources]) {
            BMLog(@"2---:%@",meSource.name);
            
            if (cell.source.itemtype == ITEMTYPECUZYITEM) {
                
                if ([meSource.themeid isEqualToString:cell.source.themeid]) {
                    isAdd = NO;
                    break;
                }
                
            }else{
                if ([meSource.name isEqualToString:cell.source.name]) {
                    isAdd = NO;
                    break;
                }
            }
        }
        
        if ([self.delegate respondsToSelector:@selector(handleSource:isAdd:)]) {
            [self.delegate handleSource:cell.source isAdd:isAdd];
        }
        UIImage  *sub = nil;
        UIImage  *unSub = nil;
        
        sub = IMGNAMED(@"bg_subscribe.png");
        unSub = IMGNAMED(@"bg_unsubscribe.png");
        
        cell.subscribeImageView.image = sub;
        for (MeSource *meSource in [[SourceManager sharedManager] meSources]) {
            
            if (meSource.itemtype == ITEMTYPECUZYITEM) {
                if ([meSource.themeid isEqualToString:cell.source.themeid]) {
                    
                    cell.subscribeImageView.image = unSub;
                    break;
                }
            }else{
                if ([meSource.name isEqualToString:cell.source.name]) {
                    
                    cell.subscribeImageView.image = unSub;
                    break;
                }
            }
        }
        
    }
    
}


#pragma mark SourceManagerDelegate
- (void)mkManagerCustomSourcesDidFinishedWithSources:(NSMutableArray *)customSources{
    if (customSources) {
        self.customSources = customSources;
        [self.tableView reloadData];
    }
}

- (void)mkManagerAllSourcesRequestDidFinishedWithSources:(NSArray *)sources{
    [self.indicatorView stopAnimating];
    if (sources) {
         self.sources = [NSMutableArray arrayWithArray:sources];
    }
    [self.tableView reloadData];
}

- (void)mkManagerAllSourcesRequestDidFailed{
    [self.indicatorView stopAnimating];
}

#pragma mark - getter
- (UIImageView *)navImageView{
    if (!_navImageView) {
        _navImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, kDefaultBottomBarHeight)];
        _navImageView.userInteractionEnabled = YES;

        _navImageView.backgroundColor = COLOR_RGB_NAV;
        [self.indicatorView setFrame:CGRectMake(CGRectGetWidth(_navImageView.frame) - 36 - 10, 10, 30, 30)];
        [_navImageView addSubview:self.indicatorView];
    }
    return _navImageView;
}
- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
    }
    return _indicatorView;
}
- (UILabel *)theTitle{
    if (!_theTitle) {
        _theTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 4, 260, 40)];
        _theTitle.backgroundColor = [UIColor clearColor];
        _theTitle.textAlignment = [Util getAlign:ALIGNTYPE_LEFT];
        _theTitle.font = FONT_TITLE(18.0f);
        _theTitle.textColor = [UIColor flatWhiteColor];
        [self.navImageView addSubview:_theTitle];
    }
    return _theTitle;
}
- (UIImageView *)bottomImageView{
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - kDefaultBottomBarHeight - _kSpaceHeight, 320, kDefaultBottomBarHeight)];
        _bottomImageView.backgroundColor = COLOR_RGB_BOTTOM;
        _bottomImageView.userInteractionEnabled = YES;
        [_bottomImageView setImage:IMGNAMED(@"bottomTabBarBackground.png")];
        UIImage *imgBack = IMGNAMED(@"btn_back.png");
        
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, floorf((_bottomImageView.bounds.size.height-imgBack.size.height)/2), imgBack.size.width, imgBack.size.height);
        [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:back];
        
        UIImage *imgTop = IMGNAMED(@"btn_top.png");
        UIButton *top = [UIButton buttonWithType:UIButtonTypeCustom];
        top.exclusiveTouch = YES;
        top.frame = CGRectMake(_bottomImageView.bounds.size.width-imgTop.size.width-10, floorf((_bottomImageView.bounds.size.height-imgTop.size.height)/2), imgTop.size.width, imgTop.size.height);
        [top addTarget:self action:@selector(tableViewDidScrollToTop) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:top];

        [back setBackgroundImage:IMGNAMED(@"btn_dis.png") forState:UIControlStateNormal];
        [back setBackgroundImage:IMGNAMED(@"btn_dis_light.png") forState:UIControlStateHighlighted];
            
        [top setBackgroundImage:IMGNAMED(@"btn_top.png") forState:UIControlStateNormal];
        [top setBackgroundImage:IMGNAMED(@"btn_top_light.png") forState:UIControlStateHighlighted];

    }
    return _bottomImageView;
}

- (UITableView *)tableView{
    if (nil == _tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,
                                                                   self.navImageView.frame.origin.y+self.navImageView.bounds.size.height,
                                                                   320,
                                                                   self.view.bounds.size.height - kDefaultBottomBarHeight-self.navImageView.frame.origin.y-self.navImageView.bounds.size.height - _kSpaceHeight)
                                                  style:UITableViewStylePlain];
        [_tableView setBackgroundColor:COLOR_BG_VIEW];
        [_tableView setDelegate: self];
        [_tableView setDataSource:self];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

@end
